<template>
  <pageTabelLayout>
    <template #pageHeader>
      <div class="my-tool-bar">
        <a-form size="small" :model="pageData" layout="inline">
            <a-form-item label="类别中文名">
              <a-input class="bacClass" placeholder="" v-model="pageData.typeName" style="width: 200px;" allow-clear />
            </a-form-item>
        </a-form>
        <Toolbar :items="pageData.btnList"  @import="importHandler" 
          @select="selectHandler" @export="exports">
        </Toolbar>
      </div>
    </template>
    <template #pageTabel>
      <!-- <a-tabs   :justify="true">
                    <a-tab-pane title="字典类别管理"> -->
      <!-- <a-table size="mini" style="height:100%"  :scrollbar="scrollbar" sticky-header @page-change="pagination.change" stripe
                                 :bordered="true" :columns="tableColumns" @change="handleChange"  :draggable="{type:'handle',width:20,fixed:true}"
                                 :row-selection="{ showCheckedAll: true, width: 50, onlyCurrent: true }"
                                 v-model:selected-keys="selectedRowKeys" :loading="pageData.pageLoading" :data="table.dataList"
                                 :pagination="false"
                                 :rowKey="rowKey" :scroll="{x:'100%',y:'100%' ,maxHeight:'100%'}">
                            <template #action="{ record }">
                                <a-button type="primary" size="small" status="warning" @click="editHandler(record)"
                                          v-if="record.sysType === 1&&pageData.isEdit">
                                    <template #icon>
                                        <icon-edit/>
                                    </template>
                                    修 改
                                </a-button>
                            </template>
                        </a-table> -->
      <!-- <AgGridVuesCopys :rowHeight="33" :headerHeight="33" :suppressCopyRowsToClipboard="true" :localeText="localeText1" rowSelection="multiple"
        @grid-ready="gridReady" style="height: 100%" :defaultColDef="defaultColDef" class="ag-theme-alpine"
        :rowData="table.dataList" :columnDefs="tc">
      </AgGridVuesCopys> -->
      <div class="w-full h-full">
        <encapsulation-agrid style="height: 100%" ref="gridOption" :configaggrid="configTable"></encapsulation-agrid>
      </div>
      <!-- </a-tab-pane>
                </a-tabs> -->
    </template>
    <!-- <paginationCopys :total="pagination.total" show-total show-jumper show-page-size @change="PageSize"
      @page-size-change="change1" :page-size="pagination.pageSize" :current="pagination.page"
      style="justify-content: center" :page-size-options="pagingList1" /> -->
    <a-drawer ok-text="保存" cancel-text="关闭" :drawer-style="{ zIndex: 9999 }" :mask-closable="false" :width="400"
      :visible="pageData.showAdd" unmountOnClose @ok="sideOk" @cancel="pageData.showAdd = false"
      :ok-loading="pageData.pageLoading">
      <template #title>
        {{ pageData.sideTitle }}
      </template>
      <div>
        <a-form ref="formRef" layout="horizontal" :model="dataForm">
          <a-form-item label-col-flex="100px" label="类别编号" field="codeType"
            :rules="[{ required: true, message: '类别编号必填' }]" :validate-trigger="['change', 'blur']"
            :disabled="dataForm.id != null">
            <a-input-number :class="{ bacClass: dataForm.id == null }" v-model="dataForm.codeType" placeholder=""
              class="input-demo" :min="0" :max="1000000000000000" />
            <!-- <a-input class="bacClass" placeholder="请输入类别编号" v-model="dataForm.codeType" @blur="inputBlur" /> -->
          </a-form-item>
          <a-form-item label-col-flex="100px" label="类别中文名" field="typeName" :validate-trigger="['change', 'blur']"
            :rules="[{ required: true, message: '类别中文名必填' }]">
            <a-input class="bacClass" placeholder="" v-model="dataForm.typeName" />
          </a-form-item>
          <a-form-item label-col-flex="100px" label="类别英文名" field="typeNameEn" :rules="[{ validator: isEng }]"
            :validate-trigger="['change', 'blur']">
            <a-input class="bacClass" placeholder="" v-model="dataForm.typeNameEn" />
          </a-form-item>
          <a-form-item label-col-flex="100px" label="备注" field="remark">
            <a-textarea class="bacClass" placeholder="" v-model="dataForm.remark" :max-length="400" allow-clear
              show-word-limit />
          </a-form-item>
        </a-form>
      </div>
    </a-drawer>
  </pageTabelLayout>
</template>

<script lang="ts">
import { post } from '@/api/http'
import { usePagination, useRowKey, useRowSelection, useTable, useTableColumn } from '@/hooks/table'

import { onMounted, reactive, ref } from 'vue'
import Toolbar from '@/components/Toolbar.vue'
import { Message, Modal } from '@arco-design/web-vue'
import { FormInstance } from '@arco-design/web-vue/es/form'
import usePermission from '@/store/modules/permission'
import emitter from '@/hooks/useEventBus'
import { localeText } from '@/api/aggridZw'
import { pagingList } from '@/api/paging'
interface ClothInfo {
  id: number | string | null
  codeType: any
  typeName: string
  typeNameEn: string
  remark: string
  sysType: number
  deteleState: string | undefined | null
  createName: string | undefined | null
  createTime: string | undefined | null
  updateName: string | undefined | null
  updateTime: string | undefined | null
}

export default {
  name: 'DictionaryCategory',
  setup() {
    function PageSize(val: any) {
      pagination.page = val
      doRefresh()
    }

    function change1(val: any) {
      pagination.pageSize = val
      doRefresh()
    }
    //查询
    function doRefresh() {
      // pageData.pageLoading = true
      // post({
      //   url: 'dict/dictType/getPage',
      //   data: {
      //     page: pagination.page,
      //     size: pagination.pageSize,
      //     deleteState: 0,
      //   },
      // })
      //   .then(({ data, code }: any) => {
      //     if (code === 200) {
      //       data.list = data.list.map(function (o: any) {
      //         o['disabled'] = o['sysType'] == 0 ? true : false
      //         return o
      //       })
      //       gridOption.value.setRowData(data.list)
      //       table.handleSuccess(data.list)
      //       pagination.setTotalSize(data.total)
      //     }
      //   })
      //   .catch(console.log)
      //   .finally(() => {
      //     pageData.pageLoading = false
      //   })
      try {
          gridOption.value.setQuery({
            deleteState: 0,
            typeName:pageData.typeName
      })
        } catch (error) {
          console.log(error);
        }
    }

    const { selectedRowKeys, onSelectionChange } = useRowSelection()
    const pagination = usePagination(doRefresh)
    const table = useTable()
    const rowKey = useRowKey('id')
    const tableColumns = useTableColumn([
      {
        title: '类别编号',
        key: 'codeType',
        dataIndex: 'codeType',
        width: 150,
      },
      {
        title: '类别中文名',
        key: 'typeName',
        dataIndex: 'typeName',
        width: 150,
      },
      {
        title: '类别英文名',
        key: 'typeNameEn',
        dataIndex: 'typeNameEn',
        width: 150,
      },
      {
        title: '备注',
        key: 'remark',
        dataIndex: 'remark',
        width: 150,
      },
      {
        title: '创建人',
        key: 'createName',
        dataIndex: 'createName',
        width: 150,
      },
      {
        title: '创建时间',
        key: 'createTime',
        dataIndex: 'createTime',
        width: 200,
      },
      {
        title: '最后修改人',
        key: 'updateName',
        dataIndex: 'updateName',
        width: 150,
      },
      {
        title: '最后修改时间',
        key: 'updateTime',
        dataIndex: 'updateTime',
        width: 150,
      },
      // {
      //   title: '操作',
      //   key: 'id',
      //   dataIndex: 'id',
      //   slotName: 'action',
      //   width: 150,
      //   fixed: 'right',
      // },
    ])
    const pageData = reactive<{
      showAdd: boolean
      sideTitle: string
      dropDownData: any
      pageLoading: boolean
      btnList: any[]
      isEdit: boolean
      typeName:any
    }>({
      showAdd: false,
      sideTitle: '新增字典类别管理',
      dropDownData: '',
      pageLoading: false,
      btnList: [],
      isEdit: false,
      typeName:'',
    })

    onMounted(() => {
      emitter.on("refresh-DictionaryCategory", () => doRefresh());
     })
    //查询
    const selectHandler = () => {
      pagination.page = 1
      doRefresh()
    }
    const addHandler = () => {
      for (var key in dataForm) {
        if (key === 'id') {
          dataForm[key] = null
        } else if (key === 'obsoleteState') {
          dataForm[key] = 0
        } else {
          dataForm[key] = ''
        }
      }
      pageData.showAdd = true
      pageData.sideTitle = '新增字典类别管理'
    }
    const dataForm = reactive<ClothInfo>({
      id: null,
      codeType: '',
      typeName: '',
      typeNameEn: '',
      remark: '',
      deteleState: '',
      createName: '',
      createTime: '',
      updateName: '',
      updateTime: '',
      sysType: 1,
    })
    const gridOption = ref()
    // const gridReady = (params: any) => {
    //   gridOption.value = params.api
    // }

    const formRef = ref<FormInstance>()
    const sideOk = () => {
      formRef.value?.validate().then((err) => {
        if (!err) {
          if (pageData.sideTitle === '新增字典类别管理') {
            pageData.pageLoading = true
            post({
              url: 'dict/dictType/insert',
              data: [dataForm],
            })
              .then((res: any) => {
                if (res.code === 200) {
                  formRef.value?.resetFields()
                  for (var key in dataForm) {
                    if (key === 'id') {
                      dataForm[key] = null
                    } else {
                      dataForm[key] = ''
                    }
                  }
                  pageData.showAdd = false

                  Message.success({
                    content: '新增成功',
                    duration: 5000,
                  })
                  doRefresh()
                } else {
                  Message.error({
                    content: res.message,
                    duration: 5000,
                  })
                }
              })
              .finally(() => {
                pageData.pageLoading = false
              })
          } else {
            pageData.pageLoading = true
            post({
              url: 'dict/dictType/update',
              data: [dataForm],
            })
              .then((res: any) => {
                if (res.code === 200) {
                  formRef.value?.resetFields()
                  pageData.showAdd = false

                  Message.success({
                    content: '修改成功',
                    duration: 5000,
                  })
                  doRefresh()
                } else {
                  Message.error({
                    content: res.message,
                    duration: 5000,
                  })
                }
              })
              .finally(() => {
                pageData.pageLoading = false
              })
          }
        }
      })
    }
    const deleteHandler = () => {
      if (gridOption.value.getSelectedRows() === 0) {
        return
      }
      Modal.confirm({
        title: '系统提示',
        content: '确认删除选中的数据?',
        onOk() {
          pageData.pageLoading = true
          post({
            url: 'dict/dictType/delete',
            data: gridOption.value.getSelectedRows().map((o: any) => {
              return o.id
            }),
          })
            .then(({ code, data }: any) => {
              if (code === 200) {
                Message.success({
                  content: '删除成功',
                  duration: 5000,
                })
                pagination.page = 1
                doRefresh()
              } else {
                Message.error({
                  content: '修改失败',
                  duration: 5000,
                })
              }
            })
            .finally(() => {
              pageData.pageLoading = false
            })
        },
      })
    }
    const editHandler = (record: ClothInfo) => {
      dataForm.id = record.id
      dataForm.codeType = record.codeType
      dataForm.typeName = record.typeName.trim()
      dataForm.typeNameEn = record.typeNameEn.trim()
      dataForm.remark = record.remark.trim()
      pageData.sideTitle = '修改字典类别管理'
      pageData.showAdd = true
    }
    //判断是否填写了中文
    const isChiese = (value: string, cb: Function) => {
      return new Promise<void>((resolve) => {
        if (window.encodeURI(value).indexOf('%') !== -1) {
          cb('填写的值不能包含中文！')
        }
        resolve()
      })
    }
    //input离开焦点 将小写转大写
    const inputBlur = () => {
      dataForm.codeType = dataForm.codeType.toUpperCase()
    }
    //导出
    const exports = () => {
      if (gridOption.value.getSelectedRows().length === 0) {
        Message.error('请先勾选')
        return
      } else {
        let idList: any = []
        gridOption.value.getSelectedRows().forEach(function (o: any) {
          idList.push(o['id'])
        })
        console.log(idList);
        
        //将表头拼接出来
        let head =
          '<th>类别编号</th><th>类别中文名</th><th>类别英文名</th><th>备注</th><th>创建人</th><th>创建时间</th><th>最后修改人</th><th>最后修改时间</th>'
        //拿到当前表格数据与勾选的行做筛选
        const  tableDataList = gridOption.value.getListData()
        let nowRow = tableDataList.filter(function (o) {
          return (
            gridOption.value
              .getSelectedRows()
              .map((o: any) => {
                return o.id
              })
              .indexOf(o['id']) !== -1
          )
        })
        let body = ''
        nowRow.forEach(function (o) {
          body += '<tr><td>' + o['codeType'] + '</td>'
          body += '<td>' + o['typeName'] + '</td>'
          body += '<td>' + o['typeNameEn'] + '</td>'
          body += '<td>' + o['remark'] + '</td>'
          body += '<td>' + o['createName'] + '</td>'
          body += '<td>' + o['createTime'] + '</td>'
          body += '<td>' + o['updateName'] + '</td>'
          body += '<td>' + o['updateTime'] + '</td>'
          body += '</tr>'
        })
        console.log(body)
        tableToXlsx(head, '字典类别管理', body)
        
      }
    }

    function tableToXlsx(head: any, filename: any, body: any) {
      const uri = 'data:application/vnd.ms-excel;base64,',
        template = `<html>
            <head><meta charset="UTF-8"></head>
            <body><table border="1"><tr>${head}</tr>${body}</table></body>
        </html>`

      const a = document.createElement('a')
      a.href = uri + window.btoa(unescape(encodeURIComponent(template)))
      a.download = filename
      a.click()
      document.removeChild(a)
    }

    const importHandler = () => {
      const inputEle: HTMLInputElement = document.createElement('input')
      inputEle.type = 'file'
      inputEle.id = 'fileUploadExcel'
      inputEle.accept =
        'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel'
      inputEle.addEventListener('change', () => {
        console.log(this)
      })
    }
    //判断只能写英文
    const isEng = (value: string, cb: Function) => {
      return new Promise<void>((resolve) => {
        var isletter = /^[a-zA-Z]+$/.test(value)
        if (!isletter) {
          cb('填写的值只能是英文！')
        }
        resolve()
      })
    }
    //设置权限
    // ['查询', '新增', '删除', '导出', '导入']
    const permissionStore = usePermission()

    if (permissionStore.hasPermisson('zdlbgl.cx')) {
      pageData.btnList.push('查询')
    }
    // if (permissionStore.hasPermisson('zdlbgl.xz')) {
    //   pageData.btnList.push('新增')
    // }
    // if (permissionStore.hasPermisson('zdlbgl.sc')) {
    //   pageData.btnList.push('删除')
    // }
    if (permissionStore.hasPermisson('zdlbgl.dc')) {
      pageData.btnList.push('导出')
    }
    // if (permissionStore.hasPermisson('zdlbgl.dr')) {
    //     pageData.btnList.push("导入")
    // }
    if (permissionStore.hasPermisson('zdlbgl.xg')) {
      pageData.isEdit = true
    }
    const handleChange = (_data: any) => {
      table.handleSuccess(_data)
    }
    let tc: any[] = tableColumns.map((o: any) => {
      let obj = {
        headerName: o.title,
        field: o.key,
        pinned: o['fixed'],
        tooltipField: o.key,
      }
      obj['width'] = 250
      if (o.slotName === 'action') {
        obj['resizable'] = false
        obj['filter'] = false
        obj['sortable'] = false
        obj['lockPosition'] = 'right'
        obj['width'] = 80
        obj['cellRenderer'] = {
          template: `<el-button style="color:#165dff;" link @click="a" v-if="f">修改</el-button>`,
          setup(props: any) {
            const a = () => {
              editHandler(props.params.data)
            }
            let f = permissionStore.hasPermisson('zdlbgl.xg')
            return {
              a,
              f,
            }
          },
        }
      }

      return obj
    })

    let a = [
      {
        showRowGroup: 'hide_def',
        headerName: '',
        checkboxSelection: true,
        headerCheckboxSelection: true,
        pinned: 'left',
        width: 50,
        resizable: false,
        filter: false,
        sortable: false,
        minWidth: 50,
        maxWidth: 50,
        lockPosition: 'left',
      },
    ]
    tc = a.concat(tc)
    let configTable = ref({
      url: 'dict/dictType/getPage', //接口路径
      queryData: {
        //接口参数
        deleteState: 0,
        typeName:pageData.typeName
      },
      // isGet:true,//是否是get请求
      // isLimit:true,//后端分页接收limit而非size
      paginationShow: true, //分页是否显示
      invokeiIterface: true, //是否调用接
      rowMultiSelectWithClick: true, //点击行是否多选
      column: tc,
      fileName: 'DictionaryCateory', //导出文件名
    })
    const defaultColDef = {
      sortable: true,
      resizable: true,
      filter: true,
      // flex: 1
    }
    const localeText1: any = ref(localeText)
    const pagingList1: any = ref(pagingList)
    return {
      pagingList1,
      localeText1,
      defaultColDef,
      tc,
      importHandler,
      deleteHandler,
      sideOk,
      formRef,
      dataForm,
      addHandler,
      selectedRowKeys,
      pagination,
      tableColumns,
      table,
      rowKey,
      pageData,
      editHandler,
      selectHandler,
      inputBlur,
      isChiese,
      exports,
      isEng,
      PageSize,
      change1,
      handleChange,
      // gridReady,
      configTable,
      gridOption
    }
  },
  components: { Toolbar,  },
}
</script>
<style scoped lang="less">
:deep(.ag-cell) {
  border-right: 1px solid #dde2eb;
}

:deep(.ag-header-cell) {
  border-right: 1px solid #dde2eb;
}

:deep(.ag-cell-value) {
  user-select: initial;
  -moz-user-select: text;
  -ms-user-select: text;
  -webkit-user-select: text;
}
</style>
